package com.ash.datasocket.simple;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Client {

    public static void main(String[] args) throws Exception {
        DatagramSocket cliSocket = new DatagramSocket();

        // 发送请求
        String sendMsg = "你好！接收方！";
        byte[] sendBuff = sendMsg.getBytes();

        // 确定发送方的IP地址及端口号，地址为本地机器地址
        int port = 71;
        InetAddress ip = InetAddress.getLocalHost();

        // 创建发送类型的数据报：
        DatagramPacket sendPacket = new DatagramPacket(sendBuff, sendBuff.length, ip, port);

        cliSocket.send(sendPacket);
        System.out.println("send complement...");

        // 接收响应
        // 确定接受反馈数据的缓冲存储器，即存储数据的字节数组
        byte[] recBuf = new byte[1024];

        // 创建接受类型的数据报
        DatagramPacket recPacket = new DatagramPacket(recBuf, recBuf.length);

        // 通过套接字接受数据
        cliSocket.receive(recPacket);

        // 解析反馈的消息，并打印
        String backMes = new String(recBuf, 0, recPacket.getLength());
        System.out.println("接受方返回的消息：" + backMes);

        // 关闭套接字
        cliSocket.close();
    }

}
